package jun.home.dailycost.dao.impl;

import java.util.Date;
import java.util.List;

import jun.home.dailycost.dao.ItemDao;
import jun.home.dailycost.domain.Category;
import jun.home.dailycost.domain.Item;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("itemDao")
public class ItemDaoImpl implements ItemDao {

	private SessionFactory sf;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sf = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public List<Item> selectAll() {
		return sf.getCurrentSession().createQuery("from Item").list();
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public List<Item> selectByCategory(Category cat) {
		return sf.getCurrentSession()
				.createQuery("from Item as item where item.cat.cid = ?")
				.setParameter(0, cat.getCid()).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public Item selectById(int id) {
		List<Item> list = sf.getCurrentSession()
				.createQuery("from Item as item where item.id = ?")
				.setParameter(0, id).list();
		if (list.size() == 0) {
			return null;
		} else {
			return list.get(0);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public List<Item> selectByDate(Date start, Date end) {
		return sf.getCurrentSession()
				.createQuery("from Item as item where item.date >= ? and item.date <= ?")
				.setParameter(0, start).setParameter(1, end).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public List<Item> selectByDateAndCategory(Date start, Date end, Category cat) {
		return sf.getCurrentSession()
				.createQuery("from Item as item where item.cat.cid = ? and item.date >= ? and item.date <= ?")
				.setParameter(0, cat.getCid()).setParameter(1, start).setParameter(2, end).list();
	}

	@Override
	@Transactional
	public void store(Item item) {
		sf.getCurrentSession().saveOrUpdate(item);
	}

	@Override
	@Transactional
	public void delete(Item item) {
		sf.getCurrentSession().delete(item);
	}

}
